import connector.driver
from connector.driver import DatabaseDriver


# 根据书籍分类名查询分类号

def get_cate_id_by_cate_name(driver: DatabaseDriver, cate_name: str):
    return driver.query_one(sql="select cate_id from category where cate_name='{}'".format(cate_name), log=True)

def get_cate_by_cate_name(driver: DatabaseDriver, cate_name: str):
    return driver.query_one(sql="select * from category where cate_name like '%{}%'".format(cate_name), log=True)


# 获取所有书籍分类
def get_cates(driver: DatabaseDriver) -> tuple:
    return driver.query_all("select * from category", log=True)


# 根据id获取类别
def get_cate_by_id(driver: DatabaseDriver, cate_id: int) -> tuple:
    return driver.query_one("select * from category where cate_id={}".format(cate_id), log=True)


# 修改分类
def update_cate(driver: DatabaseDriver, cate_id: int, cate_name: str) -> int:
    return driver.update("update category set cate_name='{}' where cate_id={}".format(cate_name, cate_id))


# 删除分类
def del_cate(driver: DatabaseDriver, cate_id: int) -> int:
    return driver.delete("delete from category where cate_id={}".format(cate_id))


# 新增分类
def add_cate(driver: DatabaseDriver, cate_id: int, cate_name: str) -> int:
    if cate_id is not None:
        # 说明自增主键
        return driver.insert("insert into category values({},'{}')".format(cate_id, cate_name))
    else:
        return driver.insert("insert into category(cate_name) values ('{}')".format(cate_name))
